package com.chinaums.open.api.parser.json;

import com.chinaums.open.api.OpenApiException;
import com.chinaums.open.api.OpenApiParser;
import com.chinaums.open.api.OpenApiRequest;
import com.chinaums.open.api.OpenApiResponse;
import com.chinaums.open.api.annotation.ApiField;
import com.chinaums.open.api.internal.util.OpenApiLogger;
import com.chinaums.open.api.internal.util.converter.Converter;
import com.chinaums.open.api.internal.util.converter.JsonConverter;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.text.ParseException;

/**
 * Created with IntelliJ IDEA.
 * User: ZHANGWEI
 * Date: 2016/12/2
 * Time: 14:37
 * 所属模块：
 * 功能说明：
 */
public class ObjectJsonParser<T extends OpenApiResponse> implements OpenApiParser<T> {

    private Class<T> class_;

    public ObjectJsonParser(Class<T> tClass) {
        this.class_ = tClass;
    }

    public T parse(String paramString) throws OpenApiException {
        Converter converter = new JsonConverter();
        try {
            return converter.toResponse(paramString,this.class_);
        } catch (IllegalAccessException e) {
            OpenApiLogger.logError(e.getCause());
        } catch (InstantiationException e) {
            OpenApiLogger.logError(e.getCause());
        } catch (ParseException e) {
            OpenApiLogger.logError(e.getCause());
        } catch (ClassNotFoundException e) {
            OpenApiLogger.logError(e.getCause());
        }
        return null;
    }

    public String validRequest(OpenApiRequest<T> openApiRequest) throws OpenApiException {
        JSONObject jsonObj = JSONObject.fromObject(openApiRequest);
        for (Class clazz = openApiRequest.getClass(); !clazz.getName().equals(
                Object.class.getName()); clazz = clazz.getSuperclass()) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                String fieldName = field.getName();
                String name = fieldName;
                String key = fieldName;
                boolean required = false;
                int length = -1;
                int minLength = -1;
                int maxLength = -1;
                if (field.isAnnotationPresent(ApiField.class)) {
                    ApiField requestMark = field
                            .getAnnotation(ApiField.class);
                    String markKey = requestMark.key();
                    if (markKey != null && !markKey.equals("")) {
                        key = markKey;
                    }
                    name = requestMark.name();
                    required = requestMark.required();
                    length = requestMark.length();
                    minLength = requestMark.minLength();
                    maxLength = requestMark.maxLength();
                    String value = jsonObj.get(key) == null ? null : jsonObj
                            .get(key).toString().trim();
                    if (StringUtils.isBlank(value) && required)
                        throw new OpenApiException(name + "[" + key + "]不能为空");
                    if (StringUtils.isNotBlank(value)) {
                        if (length != -1) {
                            if (value.length() != length)
                                throw new OpenApiException(name + "[" + key
                                        + "]长度必须为:" + length);
                        }
                        if (minLength != -1) {
                            if (value.length() < minLength)
                                throw new OpenApiException(name + "[" + key
                                        + "]长度必须大于等于:" + minLength);
                        }
                        if (maxLength != -1) {
                            if (value.length() > maxLength)
                                throw new OpenApiException(name + "[" + key
                                        + "]长度必须小于等于:" + maxLength);
                        }
                    }
                }
            }
        }
        return jsonObj.toString();
    }
}
